package cmd

import (
	"errors"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"

	"gitee.com/shaddy/k3sinstall/install"
	"gitee.com/shaddy/k3sinstall/mylog"
	"github.com/spf13/cobra"
)

func parseIpPort(hoststr string) (string, int, error) {
	if hoststr == "" {
		return "", 0, errors.New("服务器连接符错误 请确认指定服务器连接符正确 ")

	}
	hoststrs := strings.Split(hoststr, ":")
	if len(hoststrs) == 1 {
		return hoststrs[0], 22, nil
	} else {
		port, err := strconv.Atoi(hoststrs[1])
		return hoststrs[0], port, err
	}
}

var (
	MasterIPs     []string
	NodeIPs       []string
	Username      string
	Password      string
	MasterTag     string
	NodeTag       string
	WorkDir       string
	PkgFile       string
	ImageFileName string
	initCmd       = &cobra.Command{
		Use:   "init",
		Short: "Simplest way to init your k3s HA cluster",
		Long: `k3sinstall init --master 192.168.0.2 --master 192.168.0.3 --master 192.168.0.4 \
		--node 192.168.0.5 --user root --passwd your-server-password`,
		Run: func(cmd *cobra.Command, args []string) {
			//fmt.Println(NodeIPs)
			//fmt.Println(MasterIPs)
			for i := range MasterIPs {
				ip, port, err := parseIpPort(MasterIPs[i])
				if err != nil {
					mylog.Error.Panicf("解析ip地址失败 ip: %s port: %d  %s /n", ip, port, err.Error())
				}
				ipaddress := net.ParseIP(ip)
				if ipaddress == nil {
					mylog.Error.Panicf("解析ip地址失败 请确认master参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)

				}
				if port < 1 || port > 65535 {
					mylog.Error.Panicf("解析ip地址失败 请确认master参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)
				}
				MasterIPs[i] = fmt.Sprintf("%s:%d", ipaddress.String(), port)
			}
			for i := range NodeIPs {
				ip, port, err := parseIpPort(NodeIPs[i])
				if err != nil {
					mylog.Error.Panicf("解析ip地址失败 ip: %s port: %d  %s /n", ip, port, err.Error())
				}
				ipaddress := net.ParseIP(ip)
				if ipaddress == nil {
					mylog.Error.Panicf("解析ip地址失败 请确认master参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)

				}
				if port < 1 || port > 65535 {
					mylog.Error.Panicf("解析ip地址失败 请确认master参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)
				}
				NodeIPs[i] = fmt.Sprintf("%s:%d", ipaddress.String(), port)
			}

			config := &install.K3sConfig{
				Masters:       MasterIPs,
				Nodes:         NodeIPs,
				User:          Username,
				Passwd:        Password,
				ConfigFile:    ConfigFile,
				MasterNameTag: MasterTag,
				NodeNameTag:   NodeTag,
				WorkDir:       WorkDir,
				PkgFile:       PkgFile,
				ImgFile:       ImageFileName,
			}
			install.InstallHook(config)
		},
		PreRun: func(cmd *cobra.Command, args []string) {
			if len(MasterIPs) == 0 {
				mylog.Error.Panic("err no master arg !!!")
				cmd.Help()
				os.Exit(ErrorExitOSCase)
			}
			if WorkDir == "" {
				WorkDir = ConfigHome
			}
		},
	}
)

func init() {

	initCmd.Flags().StringSliceVar(&MasterIPs, "master", []string{}, "k3s multi-masters ex. 192.168.0.2:22 192.168.0.4")
	initCmd.Flags().StringSliceVar(&NodeIPs, "node", []string{}, "k3s multi-nodes ex. 192.168.0.2:22 192.168.0.4")
	initCmd.Flags().StringVar(&Username, "user", "root", "servers user name for ssh")
	initCmd.Flags().StringVar(&Password, "passwd", "123456", "password for ssh")
	initCmd.Flags().StringVar(&MasterTag, "mtag", "mhost", "pre tag for master hostname")
	initCmd.Flags().StringVar(&NodeTag, "ntag", "nhost", "pre tag for node hostname")
	initCmd.Flags().StringVar(&WorkDir, "workdir", "", "set work dir default is k3s config home")
	initCmd.Flags().StringVar(&PkgFile, "pkgfile", "k3s.gz", "set package file name")
	initCmd.Flags().StringVar(&ImageFileName, "imgfile", "k3s-airgap-images-amd64.tar.gz", "set image file name")
}
